package com.efounder.frame.manager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilemanager.R;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ProgressDialogForUpdate;
import com.efounder.utils.PublicAccoutDown;
import com.efounder.utils.PublicAccoutDownInterface;
import com.efounder.utils.ResStringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;

/**
 * Created by XinQing on 2016/12/19.
 */

public class AppAccountResDownloader {

    private DownloadAppAccountResourceListener downloadAppAccountResourceListener;
    private String downloadResURL;
    private Activity activity;
    private ProgressDialog progressDialog;
    private int appAccountID;
    private String appAccountNote = "-界面设计优化\n" +
            "-页面动态加载\n" +
            "-数据实时变化";

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0://下载并解压完成
                    downloadAppAccountResourceListener.onResourceDownloadSuccess();
                    break;
            }
        }
    };


    public AppAccountResDownloader(final Activity activity, final int appAccountID) {
        this.appAccountID = appAccountID;
        this.activity = activity;

        String loginType = EnvironmentVariable.getProperty("LoginType");
        if (null != loginType && loginType.equals("0")) {
            checkAppAccountResVersion(false,null);

        } else {
            String HttpType = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);
            String ADDRESS = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
            String PORT = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
            String PATH = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);
            String appID = EnvironmentVariable.getProperty(KEY_SETTING_APPID);
            downloadResURL = HttpType + "://" + ADDRESS + ":" + PORT + "/" + PATH + "/APPS/" + appID + "/Android/" + appAccountID + ".zip";
        }


    }

    /**
     * restful 接口检查更新
     *
     */
    public void checkAppAccountResVersion( boolean showDialog,final CheckResVerionListener checkResVerionListener) {
        final ProgressDialog dialog = new ProgressDialog(activity);
        dialog.setMessage(ResStringUtil.getString(R.string.common_text_checking));
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        if (showDialog){
            dialog.show();
        }

        AppAccountGetHttpUtil.publicUpgradeByRestFul(activity, appAccountID + "", new AppAccountRequestHttpDataUtil.PublicUpgradeByRestFulCallBack() {
            @Override
            public void upgradeResponse(int responsenum, String response) {
                try {
                    //有时候请求失败，会结束掉这个进程，杀死dialog，在这里继续dismiss会闪退
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (responsenum == 0) {
                    //服务器正常返回
                    //{"limits":[],"result":"success","appUpgrade":{"android":{"appFile":{"des":"1.修复扫码加群闪退的问题","path":"https://mobile.solarsource.cn/ospstore/OSPMobileLiveAPP/OSPMobileLiveApp.apk","version":"1.2.47"},"appResource":{"des":"","path":"","version":"0.0.53"}}},"user":{"imUserId":574,"imUserPassWord":"123456","userId":"18663788773","userName":"臧言科"}}
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString("result");
                        if (result.equals("success")) {

                            String publicUpgrade = jsonObject.getString("publicUpgrade");

                            JSONObject publicUpgradeJSONObject = new JSONObject(publicUpgrade);
                            if (!publicUpgradeJSONObject.has("android")) {
                                if (checkResVerionListener != null) {
                                    checkResVerionListener.onResultVersion("", downloadResURL);
                                }
                                return;
                            }
                            publicUpgradeJSONObject = publicUpgradeJSONObject.getJSONObject("android");
                            String version = publicUpgradeJSONObject.getString("version");
                            downloadResURL = publicUpgradeJSONObject.optString("path", "");
                            if (null == version || "".equals(version)) {
                                ToastUtil.showToast(activity, R.string.common_text_app_is_newest);
                                return;
                            }
                            appAccountNote = publicUpgradeJSONObject.optString("des","应用号资源更新");

                            if (checkResVerionListener != null) {
                                checkResVerionListener.onResultVersion(version, downloadResURL);
                            }

                            String localVersion = getLocalVersion(appAccountID);
//                                if ((null != localVersion ) ||"".equals(downloadResURL)) {
//                                    String HttpType = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);
//                                    String ADDRESS = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
//                                    String PORT = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
//                                    String PATH = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);
//                                    String appID = EnvironmentVariable.getProperty(KEY_SETTING_APPID);
//                                    downloadResURL = HttpType + "://" + ADDRESS + ":" + PORT + "/" + PATH + "/APPS/" + appID + "/Android/" + appAccountID + ".zip";
//
//                                }

                        } else {

                            ToastUtil.showToast(activity, "无法找到该应用号的信息，请联系管理员。");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (checkResVerionListener != null) {
                            checkResVerionListener.onResultVersion(null, downloadResURL);
                        }
                    }


                } else if (responsenum == 1) {
                    //网络出错
                    if (checkResVerionListener != null) {
                        checkResVerionListener.onResultVersion(null, downloadResURL);
                    }
                    ToastUtil.showToast(activity, "网络原因获取登录信息失败！");

                } else if (responsenum == 2) {
                    //未设置登录地址
                    if (checkResVerionListener != null) {
                        checkResVerionListener.onResultVersion(null, downloadResURL);
                    }
                    //  ToastUtil.showToast(activity, "程序出错了，请联系管理员！");

                }

            }
        });
    }

    /**
     * 检车版本号 a,b 都是 1.1.1的格式(固定的)
     *
     * @param a
     * @param b
     * @return
     */
    private boolean compareVersion(String a, String b) {
        String[] aarray = a.split("\\.");
        String[] barray = b.split("\\.");
        if (!aarray[0].equals(barray[0])) {
            return Integer.parseInt(aarray[0]) > Integer.parseInt(barray[0]);
        }
        if (!aarray[1].equals(barray[1])) {
            return Integer.parseInt(aarray[1]) > Integer.parseInt(barray[1]);
        }
        if (!aarray[2].equals(barray[2])) {
            return Integer.parseInt(aarray[2]) > Integer.parseInt(barray[2]);
        }
        return false;
    }

    public void downloadResource(DownloadAppAccountResourceListener listener) {
        this.downloadAppAccountResourceListener = listener;
        final PublicAccoutDown publicAccoutDown = new PublicAccoutDown(activity);

        final ProgressDialogForUpdate progressDialogForUpdate = new ProgressDialogForUpdate(activity, appAccountNote, "应用号资源文件升级",
                ResStringUtil.getString(R.string.common_text_download_now), AppContext.getInstance().getResources().getString(R.string.common_text_cancel));
        progressDialogForUpdate.showDialog();
        progressDialogForUpdate.setOnDiaLogListener(new ProgressDialogForUpdate.OnDialogListener() {
            @Override
            public void dialogPositiveListener(DialogInterface dialogInterface, int which) {
                if (downloadResURL == null) {
                    ToastUtil.showToast(activity, "该应用号无需下载资源文件");
                    progressDialogForUpdate.dismiss();
                    return;
                }
                progressDialogForUpdate.getPositiveView().setClickable(false);
                progressDialogForUpdate.getPositiveView().setTextColor(Color.parseColor("#A5A5A5"));
                publicAccoutDown.start(downloadResURL, new PublicAccoutDownInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {

                    }

                    @Override
                    public void updateProgress(float progress) {
                        progressDialogForUpdate.updateProgress((int) progress);
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        progressDialogForUpdate.dismiss();
                        // FileDeleteUtil.DeleteFolder(AppConstant.APP_ROOT + "/meeting");
                        EFAppAccountUtils.deleteAppAccountRoot(appAccountID);
                        progressDialog = new ProgressDialog(activity);
                        progressDialog.setMessage("正在解压...");
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        progressDialog.show();

                        String fileName = downloadResURL.substring(downloadResURL.lastIndexOf("/") + 1);
                        publicAccoutDown.unzipAndEncryptFile(filePath, EFAppAccountUtils.getAppAccountAppsPath() + "/" +
                                fileName);
                    }

                    @Override
                    public void error() {
                        Toast.makeText(activity, "下载应用号资源失败,自动重试。", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void stop() {

                    }

                    @Override
                    public void unZIPOVER() {

                        progressDialog.dismiss();
                        System.out.println("-------------下载并解压完成-----------------");
                        myHandler.sendEmptyMessage(0);

                    }
                });

            }

            @Override
            public void dialogNegativeListener(DialogInterface dialogInterface, int which) {
                publicAccoutDown.stopTask();
                progressDialogForUpdate.dismiss();
            }

            @Override
            public void dialogCancelListener() {
                publicAccoutDown.stopTask();
            }
        });
    }

    public String getDownloadResURL() {
        return downloadResURL;
    }

    /**
     * 下载应用号资源文件监听接口
     */
    public interface DownloadAppAccountResourceListener {

        public void onResourceDownloadSuccess();

    }

    /**
     * restfuL 检查资源文件监听接口
     */
    public interface CheckResVerionListener {

        public void onResultVersion(String version, String url);

    }

    /////////////////////////////////
    public void updateResource() {
        String loginType = EnvironmentVariable.getProperty("LoginType");
        if (null != loginType && loginType.equals("0")) {
            checkAppAccountResVersion( true,new CheckResVerionListener() {
                @Override
                public void onResultVersion(String version, String url) {
                    String localVersion = getLocalVersion(appAccountID);
                    if (localVersion != null && !localVersion.equals(version)) {
                        startDown();
                    }
                }
            });

        } else {
            startDown();
        }
    }

    private void startDown() {
        downloadResource(new DownloadAppAccountResourceListener() {
            @Override
            public void onResourceDownloadSuccess() {
                markUpdateOver(EFAppAccountUtils.getAppAccountID());
                sendBroadcast();

                activity.finish();
                if (activity instanceof EFAppAccountMainActivity) {
                    EFAppAccountMainActivity.clearData();
                }
                Intent intent = new Intent(activity, activity.getClass());
                intent.putExtra("id", activity.getIntent().getIntExtra("id", 0));
                intent.putExtra("nickName", activity.getIntent().getStringExtra
                        ("nickName"));
                activity.startActivity(intent);

                Log.i("", "");

            }
        });
    }

    public void sendBroadcast() {
        Intent intent = new Intent();
        intent.putExtra("num", "0");
        intent.putExtra("id", appAccountID);
        intent.setAction("com.efounder.updateres");
        intent.putExtra("type", "appaccountres");
        activity.sendBroadcast(intent);

    }

    //获取本地资源文件版本
    public static String getLocalVersion(int appAccountID) {
        String version = null;
        //{"CMD":"updateAppAccountRes","version":"0.0.3","updateNote":"1.应用号资源更新","isUpdate":true}
        String message = EnvironmentVariable.getProperty(EFAppAccountUtils.getAppAccountUniqueTag(appAccountID));
        version = getVersion(message);
        return version;
    }


    public static String getStructVersion(IMStruct002 struct002) {
        String version = null;
        //{"CMD":"updateAppAccountRes","version":"0.0.3","updateNote":"1.应用号资源更新","isUpdate":true}
        String message = struct002.getMessage();
        version = getVersion(message);
        return version;
    }

    private static String getVersion(String json) {
        if (json == null) return null;
        String version = null;
        try {
            JSONObject jsonObject = new JSONObject(json);
            version = jsonObject.getString("version");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return version;
    }

    public static boolean isNeedUpdate(IMStruct002 struct002) {
        boolean isUpdate = false;
        String localVersion = getLocalVersion(struct002.getFromUserId());
        String structVersion = getStructVersion(struct002);
        if (structVersion != null && !structVersion.equals(localVersion)) {
            isUpdate = true;
            //存储需要更新标记
            try {
                JSONObject jsonObject = new JSONObject(struct002.getMessage());
                jsonObject.put("isUpdate", true);
                EnvironmentVariable.setProperty(EFAppAccountUtils.getAppAccountUniqueTag(struct002.getFromUserId()), jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return isUpdate;
    }

    public static boolean isNeedUpdate(int appAccountID) {
        boolean isUpdate = false;
        String message = EnvironmentVariable.getProperty(EFAppAccountUtils.getAppAccountUniqueTag(appAccountID));
        try {
            if (message != null) {
                JSONObject jsonObject = new JSONObject(message);
                isUpdate = jsonObject.getBoolean("isUpdate");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return isUpdate;
    }

    /**
     * 标记更新完成
     */
    public static void markUpdateOver(int appAccountID) {
        String message = EnvironmentVariable.getProperty(EFAppAccountUtils.getAppAccountUniqueTag(appAccountID));
        if (message == null) return;
        try {
            JSONObject jsonObject = new JSONObject(message);
            jsonObject.put("isUpdate", false);
            EnvironmentVariable.setProperty(EFAppAccountUtils.getAppAccountUniqueTag(appAccountID), jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}
